package com.pj.point.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

public class Util {


    @SuppressLint("SdCardPath")
    private static final String SD_PATH = "/sdcard/carsonfile/pic/";
    private static final String IN_PATH = "/carsonfile/pic/";
    @SuppressLint("SdCardPath")
    private static final String SD_AUDIO_PATH = "/sdcard/audio/";
    private static final String IN_AUDIO_PATH = "/audio/pic/";
    @SuppressLint("SimpleDateFormat")
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");


    public static String getPath(Uri uri, Activity activity) {
        Cursor query = activity.getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
        query.moveToFirst();
        return query.getString(0);
    }

    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }
        try {
            filePic = new File(savePath + generateFileName() + ".png");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        Log.i("TAG", "carsonho：" + filePic.getAbsolutePath());

        return filePic.getAbsolutePath();
    }

    public static String generateFileName() {
        return UUID.randomUUID().toString();
    }

    public static String getTime(Date date){
        return format.format(date);
    }

    public static Calendar getTime(String time){
        Date date = null;
        try {
            date = format.parse(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAudioPath(Context context,Uri uri){
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }
        try {
            FileInputStream inputStream = new FileInputStream(new File(String.valueOf(uri)));
            filePic = new File(savePath + generateFileName() + ".png");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
             FileOutputStream outputStream = new FileOutputStream(filePic);
             outputStream.getChannel().transferFrom(inputStream.getChannel(),0,inputStream.getChannel().size());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return filePic.getAbsolutePath();
    }

    public static String save(Context context,Bitmap bitmap){
        Uri saveUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        if (null == saveUri || saveUri.toString().equals("")) {
            Looper.prepare();
            Toast.makeText(context, "保存失败！", Toast.LENGTH_SHORT).show();
            Looper.loop();
            return null;
        }
        try {
            OutputStream outputStream = context.getContentResolver().openOutputStream(saveUri);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)) {
                Toast.makeText(context, "保存成功！", Toast.LENGTH_SHORT).show();
                return getPathFromUri(context,saveUri);
            } else {
                Toast.makeText(context, "保存失败！", Toast.LENGTH_SHORT).show();
                return null;
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getPathFromUri(Context context,Uri uri){
        String path = "";
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()){
            int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            path = cursor.getString(index);
            cursor.close();
        }

        if (TextUtils.isEmpty(path)){
            path = getFilePathForNonMediaUri(context,uri);
        }
        return path;
    }

    public static String getFilePathForNonMediaUri(Context context, Uri uri) {
        String filePath = "";
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow("_data");
                filePath = cursor.getString(columnIndex);
            }
            cursor.close();
        }
        return filePath;
    }

}
